package com.grass.p019lv.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.alibaba.android.arouter.launcher.ARouter;
import com.androidx.p013lv.base.BaseApp;
import com.androidx.p013lv.base.BaseSdk;
import com.androidx.p013lv.base.Constance;
import com.androidx.p013lv.base.bean.AdInfoBean;
import com.androidx.p013lv.base.bean.AdListBean;
import com.androidx.p013lv.base.bean.UserInfo;
import com.androidx.p013lv.base.bean.event.LoginEvent;
import com.androidx.p013lv.base.dialog.DialogLoading;
import com.androidx.p013lv.base.glide.GlideUtils;
import com.androidx.p013lv.base.http.BaseRes;
import com.androidx.p013lv.base.http.HttpUtils;
import com.androidx.p013lv.base.http.UrlManager;
import com.androidx.p013lv.base.http.callback.HttpCallback;
import com.androidx.p013lv.base.interfaces.Key;
import com.androidx.p013lv.base.model.UserInfoModel;
import com.androidx.p013lv.base.service.AdClickService;
import com.androidx.p013lv.base.utils.AccountCacheUtils;
import com.androidx.p013lv.base.utils.ActivityUtil;
import com.androidx.p013lv.base.utils.AdUtils;
import com.androidx.p013lv.base.utils.BuildConfigUtils;
import com.androidx.p013lv.base.utils.DeviceIDUtils;
import com.androidx.p013lv.base.utils.LogUtils;
import com.androidx.p013lv.base.utils.NetUtil;
import com.androidx.p013lv.base.utils.SpUtils;
import com.androidx.p013lv.base.utils.ToastUtils;
import com.androidx.p013lv.base.utils.UiUtils;
import com.androidx.p013lv.mine.model.LoginModel;
import com.grass.p019lv.App;
import com.grass.p019lv.databinding.ActivitySplashLayoutBinding;
import com.grass.p019lv.event.RetryEvent;
import com.grass.p019lv.game.bean.GameSwitchBean;
import com.grass.p019lv.service.ClassifyService;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.model.HttpHeaders;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import okhttp3.Request;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import p000a.github.p003a.oaid.DeviceID;
import p000a.github.p003a.oaid.IGetter;
import p000a.p002b.RxPermissions;
import p023io.reactivex.Observable;
import p023io.reactivex.android.schedulers.AndroidSchedulers;
import p023io.reactivex.disposables.Disposable;
import p023io.reactivex.functions.Consumer;
import p023io.reactivex.functions.Function;
import p023io.reactivex.schedulers.Schedulers;

/* renamed from: com.grass.lv.activity.SplashActivity */
public class SplashActivity extends AppCompatActivity {
    public static String[] PERMISSIONS_STORAGE = {"android.permission.READ_PHONE_STATE", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
    public String acceptData;
    private ActivitySplashLayoutBinding binding;
    private Disposable disposable;
    private Disposable disposable2;
    private boolean isFast = true;
    boolean loadFinish = false;
    private DialogLoading loading;
    private LoginModel model;
    String url2 = "";
    private UserInfoModel userInfoModel;

    /* access modifiers changed from: protected */
    @Override // androidx.activity.ComponentActivity, androidx.core.app.ComponentActivity, androidx.appcompat.app.AppCompatActivity, androidx.fragment.app.FragmentActivity
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        getWindow().addFlags(128);
        ActivityUtil.getInstance().addActivity(this);
        ARouter.getInstance().inject(this);
        ActivitySplashLayoutBinding activitySplashLayoutBinding = (ActivitySplashLayoutBinding) DataBindingUtil.setContentView(this, R.layout.activity_splash_layout);
        this.binding = activitySplashLayoutBinding;
        activitySplashLayoutBinding.setLifecycleOwner(this);
        BaseApp.flag = 0;
        initView();
        initImmersionBar();
    }

    private void initImmersionBar() {
        ImmersionBar.with(this).titleBar(this.binding.toolbar).init();
    }

    private void initView() {
        getWindow().addFlags(1024);
        EventBus.getDefault().register(this);
        this.model = (LoginModel) new ViewModelProvider(this).get(LoginModel.class);
        DialogLoading dialogLoading = new DialogLoading(this);
        this.loading = dialogLoading;
        dialogLoading.setTvHint("選線中，請稍後...");
        checkPerMissions();
        this.model.data().observe(this, new Observer<BaseRes<UserInfo>>() {
            /* class com.grass.p019lv.activity.SplashActivity.C28961 */

            public void onChanged(BaseRes<UserInfo> baseRes) {
                if (baseRes.getCode() != 200 || baseRes.getData() == null) {
                    ToastUtils.getInstance().showWeak(baseRes.getMsg());
                } else {
                    SplashActivity.this.next(baseRes.getData());
                }
            }
        });
        UserInfoModel userInfoModel2 = (UserInfoModel) new ViewModelProvider(this).get(UserInfoModel.class);
        this.userInfoModel = userInfoModel2;
        userInfoModel2.data().observe(this, new Observer<BaseRes<UserInfo>>() {
            /* class com.grass.p019lv.activity.SplashActivity.C28992 */

            public void onChanged(BaseRes<UserInfo> baseRes) {
                if (baseRes.getCode() != 200 || baseRes.getData() == null) {
                    ToastUtils.getInstance().showWrong(baseRes.getMsg());
                } else {
                    SplashActivity.this.next(baseRes.getData());
                }
            }
        });
    }

    /* access modifiers changed from: package-private */
    public void next(UserInfo userInfo) {
        startService(new Intent(this, ClassifyService.class));
        SpUtils.getInstance().setUserInfo(userInfo);
        if (!TextUtils.isEmpty(userInfo.getToken())) {
            SpUtils.getInstance().put(Key.TOKEN, userInfo.getToken());
        }
        SpUtils.getInstance().put("domain", userInfo.getImgDomain());
        getAdInfo();
        getGameSwitch();
    }

    private void getGameSwitch() {
        HttpUtils.getInsatance().get(UrlManager.getInsatance().getGameSwitch(), new HttpCallback<BaseRes<GameSwitchBean>>("getGameSwitch") {
            /* class com.grass.p019lv.activity.SplashActivity.C29003 */

            public void onLvSuccess(BaseRes<GameSwitchBean> baseRes) {
                if (200 != baseRes.getCode()) {
                    return;
                }
                if (baseRes.getData().isOpenGame()) {
                    App.gameSwitch = true;
                } else {
                    App.gameSwitch = false;
                }
            }
        });
    }

    public void checkPerMissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            new RxPermissions(this).request(PERMISSIONS_STORAGE).subscribe(new C2964i(this));
        } else {
            chooseLineNew();
        }
    }

    public /* synthetic */ void lambda$checkPerMissions$0$SplashActivity(Boolean bool) throws Exception {
        if (!bool.booleanValue()) {
            ToastUtils.getInstance().showSigh("請允許許可權，否則無法進入app");
        } else if (NetUtil.isNetworkAvailable()) {
            chooseLineNew();
        } else {
            ToastUtils.getInstance().showWrong(UiUtils.getString(R.string.hit_no_net));
        }
    }

    public void chooseLineNew() {
        this.loading.show();
        new Thread(new Runnable() {
            /* class com.grass.p019lv.activity.SplashActivity.RunnableC29014 */

            public void run() {
                int i;
                String[] choiceLines = BuildConfigUtils.getChoiceLines();
                int i2 = 0;
                for (int i3 = 0; i3 < choiceLines.length; i3++) {
                    try {
                        i = BaseSdk.getOkHttpClient().newCall(new Request.Builder().url(choiceLines[i3] + "/api/sys/live").addHeader(HttpHeaders.HEAD_KEY_USER_AGENT, BaseSdk.UserAgent).build()).execute().code();
                    } catch (Exception e) {
                        e.printStackTrace();
                        i = 0;
                    }
                    if (200 != i) {
                        i2++;
                        LogUtils.m63e("333", "failNum==" + i2 + "====" + choiceLines[i3]);
                        if (i2 == choiceLines.length) {
                            LogUtils.m63e("333", "RetryEvent");
                            EventBus.getDefault().post(new RetryEvent());
                        }
                    } else if (SplashActivity.this.isFast) {
                        SplashActivity.this.isFast = false;
                        UrlManager.getInsatance().setBaseUrl(choiceLines[i3]);
                        LogUtils.m63e("333", "success lines[i]==" + choiceLines[i3]);
                        SplashActivity.this.getDeviceId();
                        SplashActivity.this.dialogDismiss();
                    }
                }
            }
        }).start();
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void dialogDismiss() {
        try {
            if (this.loading != null && this.loading.isShowing()) {
                this.loading.dismiss();
            }
        } catch (Exception e) {
            LogUtils.m63e("SplashActivity", e.toString());
        } catch (Throwable th) {
            this.loading = null;
            throw th;
        }
        this.loading = null;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void getDeviceId() {
        DeviceID.with(this).doGet(new IGetter() {
            /* class com.grass.p019lv.activity.SplashActivity.C29025 */

            @Override // p000a.github.p003a.oaid.IGetter
            public void onDeviceIdGetComplete(String str) {
                SplashActivity.this.login(str);
            }

            @Override // p000a.github.p003a.oaid.IGetter
            public void onDeviceIdGetError(Exception exc) {
                SplashActivity.this.login("00000000-0000-0000-0000-000000000000");
            }
        });
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void login(String str) {
        if ("00000000-0000-0000-0000-000000000000".equals(str) || "000000-000-0000-00000000".equals(str)) {
            str = AccountCacheUtils.loadCache(this);
            if (TextUtils.isEmpty(str)) {
                try {
                    str = DeviceIDUtils.toMD5(String.valueOf(UUID.randomUUID().getLeastSignificantBits() + System.currentTimeMillis()));
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                AccountCacheUtils.saveCache(this, str);
            }
        } else {
            try {
                str = DeviceIDUtils.toMD5(str);
            } catch (NoSuchAlgorithmException e2) {
                e2.printStackTrace();
            }
        }
        SpUtils.getInstance().put("DeviceIDUtils", str);
        if (!NetUtil.isNetworkAvailable()) {
            ToastUtils.getInstance().showWrong(UiUtils.getString(R.string.hit_no_net));
        } else if (TextUtils.isEmpty(SpUtils.getInstance().getString(Key.TOKEN))) {
            this.model.travelerLogin(DeviceIDUtils.getUniqueId(this), UiUtils.getClipData());
        } else {
            this.userInfoModel.getUserInfo();
        }
    }

    /* access modifiers changed from: package-private */
    public void getAdInfo() {
        HttpUtils.getInsatance().get(UrlManager.getInsatance().adverList(), new HttpCallback<BaseRes<AdListBean>>("AdList") {
            /* class com.grass.p019lv.activity.SplashActivity.C29036 */

            public void onLvSuccess(BaseRes<AdListBean> baseRes) {
                if (baseRes.getCode() == 200) {
                    AdUtils.getInstance().putAdBean(baseRes.getData());
                    AdInfoBean splash = AdUtils.getInstance().getSplash();
                    if (splash == null) {
                        SplashActivity.this.startMainUI();
                        SplashActivity.this.finish();
                        return;
                    }
                    SplashActivity splashActivity = SplashActivity.this;
                    int adId = splash.getAdId();
                    splashActivity.adShowMine(adId, SpUtils.getInstance().getString("domain") + splash.getAdImage(), splash.getAdJump());
                    return;
                }
                AdUtils.getInstance().deleteALL();
                SplashActivity.this.startMainUI();
                SplashActivity.this.finish();
            }
        });
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void startMainUI() {
        if (!SpUtils.getInstance().getUserInfo().isRecharge()) {
            ARouter.getInstance().build(Constance.MAIN_ACTIVITY).navigation();
        } else if (SpUtils.getInstance().getInt("status", 0) == 1) {
            startActivity(new Intent(getBaseContext(), MainActivity.class));
        } else if (System.currentTimeMillis() - SpUtils.getInstance().getLong(Key.TIME, 0) >= 604800000) {
            ARouter.getInstance().build(Constance.ACC_CREDENTIAL_ACTIVITY).withInt("type", 1).navigation();
        } else {
            ARouter.getInstance().build(Constance.MAIN_ACTIVITY).navigation();
        }
    }

    /* access modifiers changed from: package-private */
    public void adShowMine(final int i, String str, final String str2) {
        if (!TextUtils.isEmpty(str)) {
            GlideUtils.loadVideo(str, this.binding.imgAd);
        }
        this.binding.imgAd.setOnClickListener(new View.OnClickListener() {
            /* class com.grass.p019lv.activity.SplashActivity.View$OnClickListenerC29047 */

            public void onClick(View view) {
                try {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    intent.setData(Uri.parse(str2));
                    SplashActivity.this.startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Intent intent2 = new Intent(SplashActivity.this, AdClickService.class);
                intent2.putExtra("adId", i);
                SplashActivity.this.startService(intent2);
            }
        });
        this.binding.tvTime.setVisibility(0);
        this.binding.tvTimeClose.setVisibility(8);
        this.binding.tvTime.setClickable(false);
        this.binding.tvTimeClose.setClickable(false);
        new CountDownTimer(5000, 1000) {
            /* class com.grass.p019lv.activity.SplashActivity.CountDownTimerC29058 */

            public void onTick(long j) {
                TextView textView = SplashActivity.this.binding.tvTime;
                textView.setText((j / 1000) + "s");
            }

            public void onFinish() {
                SplashActivity.this.binding.tvTime.setVisibility(8);
                SplashActivity.this.binding.tvTimeClose.setVisibility(0);
                SplashActivity.this.binding.tvTimeClose.setClickable(true);
                SplashActivity.this.loadFinish = true;
            }
        }.start();
        this.binding.tvTimeClose.setOnClickListener(new View.OnClickListener() {
            /* class com.grass.p019lv.activity.SplashActivity.View$OnClickListenerC29069 */

            public void onClick(View view) {
                if (SplashActivity.this.loadFinish) {
                    SplashActivity.this.startActivity(new Intent(SplashActivity.this.getBaseContext(), MainActivity.class));
                    SplashActivity.this.finish();
                }
            }
        });
    }

    @Override // androidx.appcompat.app.AppCompatActivity
    public boolean onKeyDown(int i, KeyEvent keyEvent) {
        if (i == 4 || i == 3) {
            return true;
        }
        return super.onKeyDown(i, keyEvent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void loginEventListener(LoginEvent loginEvent) {
        getAdInfo();
    }

    private void dismissLoading() {
        DialogLoading dialogLoading = this.loading;
        if (dialogLoading != null && dialogLoading.isShowing()) {
            this.loading.dismiss();
        }
    }

    /* access modifiers changed from: protected */
    @Override // androidx.appcompat.app.AppCompatActivity, androidx.fragment.app.FragmentActivity
    public void onDestroy() {
        dismissLoading();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        LoginModel loginModel = this.model;
        if (loginModel != null) {
            loginModel.cancelHttp();
        }
        Disposable disposable3 = this.disposable;
        if (disposable3 != null) {
            disposable3.dispose();
            this.disposable = null;
        }
        Disposable disposable4 = this.disposable2;
        if (disposable4 != null) {
            disposable4.dispose();
            this.disposable2 = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void retryNet(RetryEvent retryEvent) {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("https://ldtest.cn-east-1.tropcdn.com/json/kuibei.json").openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.connect();
            if (httpURLConnection.getResponseCode() == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                while (true) {
                    String readLine = bufferedReader.readLine();
                    if (readLine == null) {
                        break;
                    }
                    this.acceptData += readLine;
                }
                JSONArray jSONArray = new JSONArray(this.acceptData.replace("null", ""));
                String[] strArr = new String[jSONArray.length()];
                for (int i = 0; i < jSONArray.length(); i++) {
                    strArr[i] = jSONArray.getString(i);
                }
                this.disposable2 = Observable.fromArray(strArr).map(new Function<String, String>() {
                    /* class com.grass.p019lv.activity.SplashActivity.C289811 */

                    public String apply(String str) throws Exception {
                        int i;
                        try {
                            i = BaseSdk.getOkHttpClient().newCall(new Request.Builder().url(str + "/api/sys/live").build()).execute().code();
                        } catch (Exception e) {
                            e.printStackTrace();
                            i = 0;
                        }
                        return i == 200 ? str : "";
                    }
                }).subscribeOn(Schedulers.m1118io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
                    /* class com.grass.p019lv.activity.SplashActivity.C289710 */

                    public void accept(String str) throws Exception {
                        SplashActivity.this.url2 = str;
                        SplashActivity splashActivity = SplashActivity.this;
                        if (splashActivity != null && splashActivity.binding != null && !TextUtils.isEmpty(str)) {
                            UrlManager.getInsatance().setBaseUrl(str);
                            SplashActivity.this.getDeviceId();
                            if (SplashActivity.this.disposable2 != null) {
                                SplashActivity.this.disposable2.dispose();
                                SplashActivity.this.disposable2 = null;
                            }
                            SplashActivity.this.dialogDismiss();
                        }
                    }
                }, new C2963h(this), new C2962g(this));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public /* synthetic */ void lambda$retryNet$1$SplashActivity(Throwable th) throws Exception {
        if (this.binding != null) {
            dialogDismiss();
        }
    }

    public /* synthetic */ void lambda$retryNet$2$SplashActivity() throws Exception {
        if (this.binding != null) {
            dialogDismiss();
            ToastUtils.getInstance().showWeak("選線失敗！");
        }
    }
}
